package com.pengchuang.ACS.admin.boot.component.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pengchuang.ACS.admin.api.dto.UserAuthDTO;
import com.pengchuang.ACS.admin.boot.service.impl.SysUserServiceImpl;
import com.pengchuang.ACS.common.constant.SecurityConstants;
import com.pengchuang.ACS.common.utils.R;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 权限认证管理 AOP 切面
 * @projectName: AccessControlSystem
 * @see: com.pengchuang.ACS.admin.boot.component.handler
 * @author: pc
 * @createTime: 2023/3/15 21:30
 * @version: 1.0
 */
@Aspect
@Component
public class OauthAspectHandler {

	@Resource
	private SysUserServiceImpl sysUserService;

	@Pointcut("execution(* com.pengchuang.ACS.admin.boot.controller..*.*(..))")
	public void pointCut(){
	}

	@Before("pointCut()")
	public void doBefore(JoinPoint joinPoint) throws UnsupportedEncodingException {
		// 对应admin 还是 root 权限进行 细分权限认证
		System.out.println("使用对应的权限认证");
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		HttpServletResponse response = requestAttributes.getResponse();
		String header = request.getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
		if (header == null) {
			// 普通admin
			request.setAttribute("role", "admin");
		} else {
			String decode = URLDecoder.decode(header, "UTF-8");
			JSONObject parse = JSONObject.parseObject(decode);
			String str = String.valueOf(parse.get("role"));
			// 包含了 root 权限的话 放开所有认证
			if (str.contains("root")) {
				request.setAttribute("role", "root");
			} else {
				request.setAttribute("role", "admin");
			}
		}
	}
}
